from fastapi import APIRouter, Query, Request, Depends
from sqlalchemy.orm import Session
from typing import List
from utils.response import success, fail, tableinfo
from utils.request import PageInfo, QueryWrapper
from utils.database import get_db
from app.model import PostModel
from app.schema import PostData

postController = APIRouter()

@postController.post("/add")
async def add_system_post(data: PostData, db: Session = Depends(get_db)):
    """
    增加岗位
    """
    try:
        r = PostModel.insert(db, data)
        return success("添加成功")
    except Exception as e:
        return fail("添加失败："+str(e))

@postController.post("/edit")   
async def edit_system_post(data: PostData, db: Session = Depends(get_db)):
    """
    修改岗位
    """
    try:
        post = data.dict(exclude_unset=True)
        r = PostModel.edit(db, post)
        return success("修改成功")
    except Exception as e:
        return fail("修改失败："+str(e))
    
@postController.post("/delete")   
async def delete_system_post(ids:List[int], db: Session = Depends(get_db)):
    """
    修改岗位
    """
    try:
        r = PostModel.delete(db, ids)
        return success("删除成功")
    except Exception as e:
        return fail("删除失败："+str(e))

@postController.get("/selectoptions")
async def get_post_select(db = Depends(get_db)):
    options = PostModel.get_select_options(db)
    return success("操作成功", options)


@postController.get("/get")
async def get_post(id:int,  db: Session = Depends(get_db)):
    post = PostModel.get_by_id(db, id)
    return success("操作成功", post)

@postController.get("/page")
async def get_page( page:int=Query(default=1), limit:int=Query(default=10), filter:str=Query(default='{}'), db: Session = Depends(get_db)):
    page  = PageInfo(page, limit)
    where = QueryWrapper.build_query_wrapper(filter)
    total, rows = PostModel.get_page(db, where, page)
    return tableinfo("查询成功", total, rows)